package com.scommunity.utils;

import com.scommunity.conf.MinioConf;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Component
public class MinioUtils {


    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConf minioConf;

    /**
     * 查询
     * 从数据库拿到fileName查询minio里面的文件
     * @param fileName
     * @return
     */
    public GetObjectResponse getObject(String fileName){
        //设置参数
        GetObjectArgs args = GetObjectArgs.builder()
                .bucket(minioConf.getBucketName())
                .object(fileName)
                .build();
        try {
            //使用minio的api
            GetObjectResponse response = minioClient.getObject(args);
//            System.out.println(response);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }


    /**
     * 上传文件
     * @param file
     * @return
     */
    public String putObject(MultipartFile file) {
        String fileName = UUID.randomUUID().toString().replace("-","");
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        fileName = fileName + suffix;
        try {
            InputStream is = file.getInputStream();
            PutObjectArgs args = PutObjectArgs.builder()
                .bucket(minioConf.getBucketName())
                .object(fileName)
                //输入流，文件大小，切片数（-1为不切片）
                .stream(is,file.getSize(),-1)
                .build();
            minioClient.putObject(args);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
        return fileName;
    }

    /**
     * 根据文件名删除
     * @param fileName
     */
    public void removeObject(String fileName){
        RemoveObjectArgs args = RemoveObjectArgs.builder()
                .bucket(minioConf.getBucketName())
                .object(fileName)
                .build();
        try {
            minioClient.removeObject(args);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
